<script setup lang="ts">
//引入基础组件
import { nextTick, reactive, ref } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
//引入message的api
import { getMessageUsers, getMessageTotal, putClearMessage, deletClearMessage } from '@/apis/message/index'
//引入底部tabbar组件
import TabBar from '@/components/tabbar/index.vue'
//引入消息推送icon组件
import messageIcon from '@/basePackage/pages/messagepush/components/icon-push.vue'
//引入搜索model组件
import searchModel from '@/components/search-model/index.vue'
//引入消息列表组件
import messageList from './components/messageList.vue'
import Auth from '@/components/auth/auth.vue'
import { useShopInfoStore } from '@/store/modules/shopInfo/index'
import { useScrollViewHeight } from '@/hooks'

// 可视区域滑动高度计算
const { scrollViewHeight } = useScrollViewHeight()

const $userStore = useShopInfoStore()
//定义消息列表数据 分页数据
const pages = reactive({
    current: 1,
    size: 10,
})
//定义消息列表数据
const messageListData = reactive<{ list: MessageListDataList[] }>({
    list: [],
})
//定义消息总数s
const messageTotal = ref('')
// 滑动后配置项
const options = reactive([
    {
        text: '标为已读',
        style: {
            backgroundColor: '#101010;',
        },
    },
    {
        text: '删除',
        style: {
            backgroundColor: '#4755E9',
        },
    },
])
enum MessageType {
    //文本
    TEXT = 'TEXT',
    //图片
    IMAGE = 'IMAGE',
    //商品
    PRODUCT = 'PRODUCT',
    //未及时处理的消息
    UN_HANDLE = 'UN_HANDLE',
}
//定义messageListData.list的类型
interface MessageListDataList {
    show: boolean
    lastTime: string
    lastMessage: {
        id: string
        createTime: string
        shopId: string
        adminId: string
        userId: string
        senderType: string
        receiverType: string
        messageType: MessageType
        message: string
        read: boolean
    }
    id: string
    userId: string
    nickname: string
    avatar: string
    handled: boolean
    [key: string]: any
}

onLoad(() => {
    uni.$emit('updateTitle')
    //获取消息列表
    getMessageList()
    //获取消息列表未读消息总数
    getTotal()
})
onShow(() => {
    //获取消息列表
    getMessageList()
    //获取消息列表未读消息总数
    getTotal()
})

/**
 * 请求消息列表
 */
const getMessageList = async () => {
    await nextTick()
    //获取消息列表
    const data = await getMessageUsers('', { current: 1, size: 1000, chatWithType: 'PLAT_FORM' }, $userStore.shopInfo.id)

    if (data.code === 200) {
        data.data.records.forEach((item: any) => {
            item.show = false
        })
        messageListData.list = data.data.records
        console.log(messageListData.list)
    } else {
        uni.showToast({
            title: data.msg || '获取消息列表失败',
            icon: 'none',
        })
    }
}
/**
 * 请求消息列表未读消息总数
 */
const getTotal = async () => {
    //获取消息列表
    const data = await getMessageTotal()
    console.log(data)
    if (data.code === 200) {
        messageTotal.value = data.data
    } else {
        uni.showToast({
            title: '获取消息列表失败',
            icon: 'none',
        })
    }
}
/**
 * 清除所有未读消息
 */
const handleClearMessage = async () => {
    //获取消息列表
    const data = await putClearMessage()
    console.log(data)
    if (data.code === 200) {
        uni.showToast({
            title: '清除成功',
            icon: 'none',
        })
        //获取消息列表
        getMessageList()
        //获取消息列表未读消息总数
        getTotal()
    } else {
        uni.showToast({
            title: '清除失败',
            icon: 'none',
        })
    }
}
/**
 *  滑动后点击事件
 */
const click = async (index: number, index1: number) => {
    if (index1 === 1) {
        // messageListData.list.splice(index, 1)
        let usrid = messageListData.list[index].chatWithUserInfo.userId
        handleDeletMessage(usrid)

        console.log('删除', usrid)
    } else {
        messageListData.list[index].show = false
        messageListData.list[index].lastMessage.read = true

        console.log('消息变成以读')
    }
}
/**
 * 删除消息
 */
const handleDeletMessage = async (useid: string) => {
    const res = await deletClearMessage(useid)
    console.log(res)
    if (res.code === 200) {
        uni.showToast({
            title: '删除成功',
            icon: 'none',
        })
        //获取消息列表
        getMessageList()
        //获取消息列表未读消息总数
        getTotal()
    } else {
        uni.showToast({
            title: '删除失败',
            icon: 'none',
        })
    }
}

/**
 *  组件触发打开状态时
 * @param {*} index
 */
const open = (index: number) => {
    messageListData.list[index].show = true
    messageListData.list.forEach((val: any, idx: number) => {
        if (index !== idx) messageListData.list[idx].show = false
    })
}
/**
 * 获取搜索用户数据
 */
const handleSearchUserMessage = (value: any) => {
    console.log(value)
    if (value) {
        if (value.length === 0) {
            uni.showToast({
                title: '未搜索到相关用户',
                icon: 'none',
            })
        }
        messageListData.list = value
    } else {
        getMessageList()
    }
}
</script>

<template>
    <scroll-view :scroll-y="true" :style="{ height: `${scrollViewHeight}` }">
        <view class="content">
            <Auth></Auth>
            <view class="content__title">
                <view class="content__title--one"
                    >消息
                    <span class="smalltitle">({{ messageTotal }})</span>
                </view>
                <view class="content__title--two">
                    <u-icon name="edit-pen" color="#999999" size="28"></u-icon>
                    <span class="smalltitle" @click="handleClearMessage">清除未读</span>
                </view>
                <view class="content__title--three">
                    <message-icon></message-icon>
                </view>
            </view>
            <view class="content__search">
                <search-model :title="'搜索（用户名）'" :searchtype="1" @search-enter="handleSearchUserMessage"></search-model>
            </view>
            <view class="content__messagelist">
                <u-swipe-action
                    v-for="(item, index) in messageListData.list"
                    :key="item"
                    :index="index"
                    :show="item.show"
                    :options="options"
                    btn-width="160"
                    @click="click"
                    @open="open"
                >
                    <message-list :data="item"></message-list>
                </u-swipe-action>
            </view>
        </view>
    </scroll-view>
    <TabBar></TabBar>
</template>

<style lang="scss" scoped>
@include b(content) {
    display: flex;
    flex-direction: column;
    @include e(title) {
        height: 106rpx;
        display: flex;
        align-items: flex-end;
        @include m(one) {
            color: rgba(51, 51, 51, 1);
            font-size: 72rpx;
            margin-left: 44rpx;
            font-weight: 700;
        }
        @include m(two) {
            color: rgba(153, 153, 153, 1);
            margin-right: 184rpx;
        }
        @include m(three) {
            margin-left: 20rpx;
            flex: 1;
        }
    }
    @include e(search) {
        height: 130rpx;
        padding: 28rpx 34rpx 10rpx 34rpx;
        margin-bottom: 10rpx;
    }
    @include e(messagelist) {
        width: 100%;
        flex: 1;
        border-radius: 50rpx 50rpx 0 0;
        background-color: rgba(252, 252, 252, 1);
        // margin-bottom: 100rpx;
        @include m(main) {
            height: 854rpx;
            // padding: 42rpx 32rpx 0 36rpx;
        }
    }
}

.smalltitle {
    font-size: 28rpx;
}
</style>
